import { bindable, containerless } from 'aurelia-framework';

@containerless
export class EmProjectCreate {

    users = nsCtx.users;
    loginUser = nsCtx.loginUser;

    project = {
        name: '',
        website: '',
        leader: this.loginUser.username,
        operator: this.loginUser.username,
    };

    @bindable key;
    keyRegex = /^[A-Z]{0,10}$/;

    keyChanged(news, old) {
        this.oldKey = old;
        if (news && !this.keyRegex.test(news)) {
            this.key = this._getOldKey();
        }
    }

    _getOldKey() {
        if (!this.keyRegex.test(this.oldKey)) {
            this.oldKey = '';
        }

        return this.oldKey;
    }

    show() {
        this.emModal.show({
            hideOnApprove: false,
            autoDimmer: true
        });
    }

    _reset() {
        this.project = {
            name: '',
            desc: '',
            leader: this.loginUser.username,
            operator: this.loginUser.username,
        };
        this.key = '';
    }

    showHandler() {
        this._reset();
    }
    approveHandler(modal) {
        $.post('/admin/task/project/create', {
            name: this.project.name,
            key: this.key,
            website: this.project.website,
            leader: this.project.leader,
            operator: this.project.operator,
        }, (data) => {
            if (data.success) {
                modal.hide();
                toastr.success('创建项目成功!');
                ea.publish(nsCons.EVENT_TASK_PROJECT_CREATED, {
                    project: data.data
                });
            } else {
                modal.hideDimmer();
                toastr.error(data.data, '创建项目失败!');
            }
        });
    }
}
